<template>
  <div>
    <div>
      <div style="padding: 20px">
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item label="名称">
            <el-input v-model="queryParams.name" placeholder="请输入名称" clearable/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :icon="Search" @click="initPageData">搜索</el-button>
            <el-button :icon="Refresh" @click="handleReset">重置</el-button>
          </el-form-item>

        </el-form>
      </div>
      <!--  增删改按钮组 -->

      <div>
        <el-button type="primary" plain :icon="Plus" @click="handleShowSaveDialog">新增</el-button>

        <el-button type="success" plain :icon="Edit" @click="handleShowEditDialog(scope.row)">
          修改
        </el-button>

        <el-button type="danger" plain :icon="Delete" @click="handleBatchUnit">批量删除</el-button>
      </div>
      <!--列表-->

      <div>
        <el-table @selection-change="handleSelectChange" :data="list" stripe style="width: 100%;margin-top: 10px;">
          <el-table-column type="selection" width="55"/>
          <el-table-column prop="name" label=" 名称"/>

          <el-table-column prop="createTime" label="创建时间"/>
          <el-table-column label="操作" min-width="120">
            <template #default="scope">
              <el-button link type="primary" size="small" @click="handleShowEditDialog(scope.row)">
                修改
              </el-button>
              <el-button link type="primary" size="small" @click="handleDelUnit(scope.row.name,scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
            v-show="total > 0"
            :total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="initPageData"
        />
      </div>
<!--新增、更新 对话框-->
    </div>
    <div>
      <el-dialog v-model="saveDialogFormVisible"  :title="title"  width="500">
        <el-form>
          <el-form-item label="名称" :label-width='formLabelWidth'>
            <el-input v-model="unit.name" autocomplete="off"/>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="saveDialogFormVisible = false" >取消</el-button>
            <el-button type="primary" @click="handleSaveOrUpdate">
              确定
            </el-button>
          </div>
        </template>
      </el-dialog>


    </div>


  </div>
</template>

<script setup>
import {Search, Refresh, Plus, Edit, Delete} from '@element-plus/icons-vue'
import {listUnits, delUnits,saveUnit , getUnitById , updateUnit} from '@/api/product/unit.js'
import {ElMessage, ElMessageBox} from "element-plus";

//1、查询页面数据：
// 页面初始化时发起异步请求加载品牌分页列表
onMounted(() => {
  initPageData()
})
//加载数据的函数：同步阻塞执行
const initPageData = async () => {
  //  异步请求 ，从返回的对象中获取它的code  rows和total三个属性值
  const {rows, total: t} = await listUnits(queryParams.value)
  //list接收查询到的分页列表
  list.value = rows; //使用响应式对象的value接收数据
  total.value = t;
}
//分页列表数据
const list = ref([])
const total = ref(100)
const queryParams = ref({
  pageNum: 1,
  pageSize: 3,
  searchValue: null
})
//重置按钮事件函数
const handleReset = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 3,
    name: null
  }
  initPageData()
}
//2、删除品牌
const handleDelUnit = (name, ids) => {
  //弹出确认删除的提示
  ElMessageBox.confirm(
      `正在删除单位 ${name},是否继续?`,
      '删除确认',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        await delUnits(ids)
        ElMessage.success("删除成功")
        //刷新页面数据
        initPageData();
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })

}
//3、批量删除
const handleBatchUnit = () => {
  //1、判断是否选中了要删除的记录
  if (!selectRows.value || selectRows.value.length === 0) {
    ElMessage.warning('请选择要删除的行')
    return
  }
  //2、获取选中记录的id列表 拼接为 逗号分割的字符串
  let ids = selectRows.value.map(row => row.id).join(',')
  let names = selectRows.value.map(row => row.name).join('、')
  // console.log(ids)
  //3、调用上面的函数删除
  handleDelUnit(names, ids)

}
//4、表格的行选中状态变化时的回调
const selectRows = ref([]) //接收选中要删除行的变量
const handleSelectChange = (newSelection) => {
  // console.log('表格选中行变化了：',newSelection)
  selectRows.value = newSelection;
}

//5、新增按钮事件函数： 弹出新增对话框
const handleShowSaveDialog = () => {
  title.value = '新增单位'
  //解决缓存问题
  unit.value = {}
  saveDialogFormVisible.value = true
}
const saveDialogFormVisible = ref(false)
const formLabelWidth = ref('120px')
const unit = ref({}) //新增对话框接收新增数据的对象
const title = ref('新增单位') //对话框标题

//6、对话框提交按钮事件函数： 提交品牌数据保存
const handleSave = async ()=>{
  await saveUnit(unit.value)
  ElMessage.success('新增成功')
  initPageData()
  //关闭对话框
  saveDialogFormVisible.value = false
}
//7、修改按钮事件函数：  查询要修改的品牌信息 弹出对话框展示
const handleShowEditDialog = async (row)=>{

  //查询要修改的品牌
  title.value = '更新单位'
  const {data} = await getUnitById(row.id)
  unit.value = data //使用新增修改对话框绑定的变量接收 查询到的品牌
  //弹出对话框
  saveDialogFormVisible.value = true
}
//8、提交修改请求
const handleUpdate = async  ()=>{
  await updateUnit(unit.value)
  initPageData()
  ElMessage.success('更新成功')
  saveDialogFormVisible.value = false
}
//9、新增、更新对话框 提交按钮的事件函数
const handleSaveOrUpdate = ()=>{
  if(unit.value.id){
    //更新
    handleUpdate()
  }else{
    //新增
    handleSave()
  }
}
</script>

<style scoped>

</style>